from flask import Flask, jsonify, request
from flask_cors import CORS
import sys
import os
import json
import threading
import time
from datetime import datetime
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 添加项目根目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 导入新的智能体架构
from src.agent.agent_orchestrator import AgentOrchestrator
from src.agent.agent_factory import AgentFactory
from src.agent.workflow_config import WORKFLOW_CONFIGS, validate_workflow_input

# 初始化协调器
orchestrator = AgentOrchestrator()

# 存储热点数据和趋势分析数据的全局变量
hotspot_data = {}
trend_analysis_data = {}
last_update_time = None
is_fetching = False

def initialize_orchestrator():
    """初始化智能体协调器"""
    global orchestrator
    
    try:
        # 构建配置文件路径
        config_path = os.path.join(os.path.dirname(__file__), '..', 'src', 'agent', 'config.json')
        
        # 创建并注册所有智能体
        agents = AgentFactory.create_all_agents(config_path)
        for agent_name, agent in agents.items():
            orchestrator.register_agent(agent)
        
        # 注册工作流
        for workflow_name, config in WORKFLOW_CONFIGS.items():
            orchestrator.register_workflow(workflow_name, config["agents"])
        
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 智能体协调器初始化完成")
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 可用工作流: {list(WORKFLOW_CONFIGS.keys())}")
        
    except Exception as e:
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 智能体协调器初始化失败: {e}")
        import traceback
        traceback.print_exc()

def fetch_weibo_data():
    """获取多平台热点数据并更新热点数据和趋势分析数据"""
    global hotspot_data, trend_analysis_data, last_update_time, is_fetching
    
    if is_fetching:
        print("正在获取数据中，跳过此次请求") 
        return
    
    is_fetching = True
    try:
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始获取多平台热点数据和趋势分析数据...")
        
        # 使用full_analysis工作流，包含趋势分析
        result = orchestrator.execute_workflow("full_analysis", {})
        
        if result["success"]:
            # 从工作流结果中提取分类数据和趋势分析数据
            final_output = result["final_output"]
            classified_data = final_output.get("SummaryGenerationAgent_result", {})
            trend_data = final_output.get("TrendAnalysisAgent_result", {})
            
            # 更新热点数据
            if classified_data:
                hotspot_data = classified_data
                
                # 计算总数据条数
                total_count = 0
                for platform in ['weibo', 'toutiao', 'douyin']:
                    if platform in classified_data and 'data' in classified_data[platform]:
                        total_count += len(classified_data[platform]['data'])
                
                print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 成功获取分类热点数据，共 {total_count} 条")
            else:
                print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 智能体未生成有效分类数据")
                hotspot_data = {}
            
            # 更新趋势分析数据
            if trend_data:
                trend_analysis_data = trend_data
                print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 成功获取趋势分析数据")
            else:
                print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 智能体未生成有效趋势分析数据")
            
            last_update_time = datetime.now()
            print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 工作流执行详情: 成功率 {result['success_rate']:.1%}, 总耗时 {result['workflow_execution_time']:.2f}s")
        else:
            print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 智能体工作流执行失败")
            print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 失败详情: {result}")
            hotspot_data = {}
            
    except Exception as e:
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 获取多平台热点数据失败: {e}")
        import traceback
        traceback.print_exc()
        hotspot_data = {}
    finally:
        is_fetching = False

def start_periodic_fetch():
    """启动定时获取任务"""
    def periodic_task():
        while True:
            fetch_weibo_data()
            # 等待10分钟
            time.sleep(600)  # 10分钟 = 600秒
    
    # 在后台线程中运行定时任务
    thread = threading.Thread(target=periodic_task, daemon=True)
    thread.start()
    print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 已启动定时获取任务，每10分钟获取一次微博数据")

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    return jsonify({
        'status': 'ok',
        'message': '后端服务运行正常',
        'timestamp': datetime.now().isoformat(),
        'agent_system': '新架构已启用'
    })

@app.route('/api/hotspots', methods=['GET'])
def get_hotspots():
    """获取热点数据（从缓存）"""
    global hotspot_data, last_update_time
    
    return jsonify({
        'success': True,
        'data': hotspot_data,
        'count': len(hotspot_data),
        'last_update': last_update_time.isoformat() if last_update_time else None,
        'is_fetching': is_fetching
    })

@app.route('/api/hotspots/fetch-now', methods=['POST'])
def fetch_now():
    """立即获取微博数据"""
    global is_fetching
    
    if is_fetching:
        return jsonify({
            'success': False,
            'message': '正在获取数据中，请稍后再试'
        }), 429
    
    # 在后台线程中执行获取任务
    thread = threading.Thread(target=fetch_weibo_data, daemon=True)
    thread.start()
    
    return jsonify({
        'success': True,
        'message': '已开始获取最新微博数据，请稍后刷新查看'
    })

@app.route('/api/hotspots/refresh', methods=['POST'])
def refresh_hotspots():
    """强制刷新热点数据和趋势分析数据"""
    global hotspot_data, trend_analysis_data, last_update_time
    
    # 保留现有数据，只是重新加载
    original_hotspot_data = hotspot_data.copy()
    original_trend_data = trend_analysis_data.copy()
    
    try:
        # 尝试重新获取数据
        fetch_weibo_data()
        
        # 如果新获取的数据为空，恢复原有数据
        if not hotspot_data:
            hotspot_data = original_hotspot_data
            trend_analysis_data = original_trend_data
            return jsonify({
                'success': True,
                'message': '刷新失败，已恢复原有数据'
            })
        
        return jsonify({
            'success': True,
            'message': '数据刷新成功'
        })
    except Exception as e:
        # 发生异常时恢复原有数据
        hotspot_data = original_hotspot_data
        trend_analysis_data = original_trend_data
        return jsonify({
            'success': False,
            'message': f'刷新失败: {str(e)}，已恢复原有数据'
        })

@app.route('/api/copywriting/generate', methods=['POST'])
def generate_copywriting():
    """生成多平台文案"""
    try:
        data = request.get_json()
        
        # 验证必需参数
        required_fields = ['hotspot_title', 'platforms', 'styles']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'success': False,
                    'message': f'缺少必要参数: {field}'
                }), 400
        
        # 使用新的智能体架构执行工作流
        input_data = {
            "hotspot_title": data['hotspot_title'],
            "hotspot_content": data.get('hotspot_content', ''),
            "platforms": data['platforms'],
            "styles": data['styles']
        }
        
        result = orchestrator.execute_workflow("content_creation", input_data)
        
        if result["success"]:
            copywriting_result = result["final_output"].get("CopywritingGenerationAgent_result", {})
            
            # 确保响应使用UTF-8编码
            response = jsonify({
                'success': True,
                'data': copywriting_result,
                'workflow_details': {
                    'success_rate': result['success_rate'],
                    'execution_time': result['workflow_execution_time']
                }
            })
            response.headers['Content-Type'] = 'application/json; charset=utf-8'
            return response
        else:
            return jsonify({
                'success': False,
                'message': f'文案生成工作流执行失败: {result}'
            }), 500
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'文案生成失败: {str(e)}'
        }), 500

@app.route('/api/trends/analyze', methods=['POST'])
def analyze_trends():
    """趋势分析API端点"""
    try:
        data = request.get_json()
        
        # 使用趋势分析工作流
        input_data = {
            "include_word_cloud": data.get('include_word_cloud', True),
            "include_stats": data.get('include_stats', True),
            "include_trends": data.get('include_trends', True)
        }
        
        result = orchestrator.execute_workflow("trend_analysis", input_data)
        
        if result["success"]:
            trend_result = result["final_output"].get("TrendAnalysisAgent_result", {})
            
            response = jsonify({
                'success': True,
                'data': trend_result,
                'workflow_details': {
                    'success_rate': result['success_rate'],
                    'execution_time': result['workflow_execution_time']
                }
            })
            response.headers['Content-Type'] = 'application/json; charset=utf-8'
            return response
        else:
            return jsonify({
                'success': False,
                'message': f'趋势分析工作流执行失败: {result}'
            }), 500
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'趋势分析失败: {str(e)}'
        }), 500

@app.route('/api/publish/execute', methods=['POST'])
def publish_content():
    """执行内容发布功能"""
    try:
        data = request.get_json()
        
        # 验证必需参数
        required_fields = ['hotspot_title', 'platforms', 'styles', 'platforms_to_publish']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'success': False,
                    'message': f'缺少必要参数: {field}'
                }), 400
        
        # 准备工作流输入数据
        input_data = {
            "hotspot_title": data['hotspot_title'],
            "hotspot_content": data.get('hotspot_content', ''),
            "platforms": data['platforms'],
            "styles": data['styles'],
            "platforms_to_publish": data['platforms_to_publish'],
            "publish_schedule": data.get('publish_schedule', 'immediate')
        }
        
        # 执行内容发布工作流
        result = orchestrator.execute_workflow("content_publishing", input_data)
        
        if result["success"]:
            # 获取发布结果
            publish_result = result["final_output"].get("PublishAgent_result", {})
            copywriting_result = result["final_output"].get("CopywritingGenerationAgent_result", {})
            
            # 返回成功响应
            response = jsonify({
                'success': True,
                'publish_results': publish_result,
                'copywriting_data': copywriting_result,
                'workflow_details': {
                    'success_rate': result['success_rate'],
                    'execution_time': result['workflow_execution_time']
                }
            })
            response.headers['Content-Type'] = 'application/json; charset=utf-8'
            return response
        else:
            return jsonify({
                'success': False,
                'message': f'内容发布工作流执行失败',
                'error_details': result.get('error', 'Unknown error')
            }), 500
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            'success': False,
            'message': f'内容发布失败: {str(e)}'
        }), 500

@app.route('/api/publish/test', methods=['POST'])
def test_publish():
    """测试发布功能，不实际发布内容"""
    try:
        data = request.get_json()
        
        # 简单验证参数
        platforms = data.get('platforms_to_publish', ["weibo", "douyin", "wechat"])
        
        # 模拟发布测试结果
        test_results = {}
        for platform in platforms:
            test_results[platform] = {
                "success": True,
                "message": f"测试发布到{platform}平台成功",
                "timestamp": datetime.now().isoformat(),
                "is_real_publish": False,
                "platform_info": {
                    "name": platform,
                    "status": "connected",
                    "test_mode": True
                }
            }
        
        return jsonify({
            'success': True,
            'message': '发布测试成功完成',
            'test_results': test_results,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'发布测试失败: {str(e)}'
        }), 500

@app.route('/api/trends/wordcloud', methods=['GET'])
def get_word_cloud():
    """获取词云数据（优先从缓存读取，缓存不存在则执行工作流）"""
    global trend_analysis_data
    
    try:
        # 优先从缓存获取词云数据
        if trend_analysis_data and "word_cloud" in trend_analysis_data:
            word_cloud = trend_analysis_data.get("word_cloud", [])
            print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 从缓存获取词云数据，共 {len(word_cloud)} 个关键词")
            return jsonify({
                'success': True,
                'data': word_cloud,
                'from_cache': True
            })
        
        # 缓存不存在，执行趋势分析工作流
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 缓存中无词云数据，执行趋势分析工作流")
        result = orchestrator.execute_workflow("trend_analysis", {
            "include_word_cloud": True,
            "include_stats": False,
            "include_trends": False
        })
        
        if result["success"]:
            trend_data = result["final_output"].get("TrendAnalysisAgent_result", {})
            word_cloud = trend_data.get("word_cloud", [])
            
            # 更新缓存
            if word_cloud:
                trend_analysis_data["word_cloud"] = word_cloud
            
            return jsonify({
                'success': True,
                'data': word_cloud,
                'from_cache': False
            })
        else:
            return jsonify({
                'success': False,
                'message': '获取词云数据失败'
            }), 500
            
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取词云数据失败: {str(e)}'
        }), 500

@app.route('/api/trends/stats', methods=['GET'])
def get_trend_stats():
    """获取趋势统计数据（优先从缓存读取，缓存不存在则执行工作流）"""
    global trend_analysis_data
    
    try:
        # 优先从缓存获取统计数据
        if (trend_analysis_data and 
            "today_stats" in trend_analysis_data and 
            "user_coverage_trend" in trend_analysis_data and
            "platform_trends" in trend_analysis_data):
            print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 从缓存获取趋势统计数据")
            return jsonify({
                'success': True,
                'data': {
                    'today_stats': trend_analysis_data.get("today_stats", {}),
                    'user_coverage_trend': trend_analysis_data.get("user_coverage_trend", {}),
                    'platform_trends': trend_analysis_data.get("platform_trends", {})
                },
                'from_cache': True
            })
        
        # 缓存不存在，执行趋势分析工作流
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 缓存中无统计数据，执行趋势分析工作流")
        result = orchestrator.execute_workflow("trend_analysis", {
            "include_word_cloud": False,
            "include_stats": True,
            "include_trends": True
        })
        
        if result["success"]:
            trend_data = result["final_output"].get("TrendAnalysisAgent_result", {})
            
            # 更新缓存
            if trend_data:
                if "today_stats" in trend_data:
                    trend_analysis_data["today_stats"] = trend_data["today_stats"]
                if "user_coverage_trend" in trend_data:
                    trend_analysis_data["user_coverage_trend"] = trend_data["user_coverage_trend"]
                if "platform_trends" in trend_data:
                    trend_analysis_data["platform_trends"] = trend_data["platform_trends"]
            
            return jsonify({
                'success': True,
                'data': {
                    'today_stats': trend_data.get("today_stats", {}),
                    'user_coverage_trend': trend_data.get("user_coverage_trend", {}),
                    'platform_trends': trend_data.get("platform_trends", {})
                },
                'from_cache': False
            })
        else:
            return jsonify({
                'success': False,
                'message': '获取趋势统计数据失败'
            }), 500
            
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取趋势统计数据失败: {str(e)}'
        }), 500

# 新的API端点 - 智能体系统管理
@app.route('/api/agents/status', methods=['GET'])
def get_agents_status():
    """获取智能体状态"""
    try:
        status = orchestrator.get_agent_status()
        return jsonify({
            'success': True,
            'data': status
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取智能体状态失败: {str(e)}'
        }), 500

@app.route('/api/workflows', methods=['GET'])
def get_available_workflows():
    """获取可用工作流"""
    try:
        workflows = orchestrator.get_available_workflows()
        return jsonify({
            'success': True,
            'data': workflows
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取工作流失败: {str(e)}'
        }), 500

@app.route('/api/workflow/execute', methods=['POST'])
def execute_workflow():
    """执行工作流"""
    try:
        data = request.get_json()
        workflow_name = data.get('workflow_name')
        input_data = data.get('input_data', {})
        
        if not workflow_name:
            return jsonify({
                'success': False,
                'message': '缺少工作流名称'
            }), 400
        
        if workflow_name not in WORKFLOW_CONFIGS:
            return jsonify({
                'success': False,
                'message': f'工作流 {workflow_name} 不存在'
            }), 400
        
        # 验证输入数据
        if not validate_workflow_input(workflow_name, input_data):
            return jsonify({
                'success': False,
                'message': f'工作流 {workflow_name} 输入数据验证失败'
            }), 400
        
        # 执行工作流
        result = orchestrator.execute_workflow(workflow_name, input_data)
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'工作流执行失败: {str(e)}'
        }), 500

def calculate_time_display(timestamp):
    """计算时间显示"""
    if not timestamp:
        return '刚刚'
    
    try:
        event_time = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
        now = datetime.now().replace(tzinfo=event_time.tzinfo) if event_time.tzinfo else datetime.now()
        diff = now - event_time
        
        if diff.total_seconds() < 60:
            return '刚刚'
        elif diff.total_seconds() < 3600:
            return f'{int(diff.total_seconds() / 60)}分钟前'
        elif diff.total_seconds() < 86400:
            return f'{int(diff.total_seconds() / 3600)}小时前'
        else:
            return f'{int(diff.total_seconds() / 86400)}天前'
    except:
        return '刚刚'

def extract_tags_from_content(content):
    """从内容中提取标签"""
    if not content:
        return ['热点']
    
    # 简单关键词提取
    common_tags = ['科技', 'AI', '娱乐', '社会', '时事', '健康', '职场', '研究', '艺术', '体育', '财经']
    found_tags = []
    
    for tag in common_tags:
        if tag in content:
            found_tags.append(tag)
    
    return found_tags[:3] if found_tags else ['热点']

if __name__ == '__main__':
    print("启动热点数据API服务...")
    print("访问 http://localhost:5001/api/health 检查服务状态")
    print("访问 http://localhost:5001/api/hotspots 获取热点数据")
    
    # 初始化智能体协调器
    initialize_orchestrator()
    
    # 启动定时获取任务
    start_periodic_fetch()
    
    app.run(host='0.0.0.0', port=5001, debug=True)
